<template>
  <div class="box_body">
    <!-- 标题 -->
    <div class="heade-title">
      <dv-decoration-11 style="width: 260px; height: 50px">
        基金大屏展示平台
      </dv-decoration-11>
    </div>

    <!-- 我的基金 -->
    <div
      class="tag-hold animate__animated animate__bounceInUp"
      :class="{ headerIsMargintop: isMarginTop }"
    >
      <!-- 顶部装饰图  -->
      <dv-decoration-3
        style="width: 100px; height: 30px"
        v-show="!isMarginTop"
      />
      <!-- 时间 -->
      <dv-decoration-9 style="width: 150px; height: 30px" v-show="!isMarginTop">
        <span class="timestyle"><i>{{ nowTime }}</i> </span>
      </dv-decoration-9>

      <!-- 右侧添加文字 -->
      <div class="updatetxt">
        <!-- 添加 -->
        <span @click="addFund()" style="margin-right: 15px">
          <i class="el-icon-plus"></i> 添加
        </span>
        <!-- 删除 -->
        <span @click="showRemove()" style="margin-right: 15px">
          <i class="el-icon-delete"></i>
          {{ showRemoveBtn ? "取消删除" : "删除" }}
        </span>
        <!-- 刷新 -->
        <span @click="update()" style="margin-right: 15px">
          <i class="el-icon-refresh"></i> 刷新
        </span>
      </div>
    </div>
    <!-- 我的基金基金走势图 -->
    <div
      id="isShow"
      v-show="isShow"
      class="animate__animated animate__bounceInUp"
    >
      <el-row :gutter="10">
        <el-col
          :md="8"
          :sm="12"
          :xs="24"
          v-for="(holdUrl, index) in imageHoldData"
          :key="index"
          class="el_col_relative"
        >
          <div class="animate__animated animate__flipInY margin-bottom">
            <el-image
              :src="holdUrl.url"
              @click="
                dialogVisible = true;
                dialogImgUrl = holdUrl.url;
              "
              class="fundImage"
            >
            </el-image>
          </div>
          <!-- 删除按钮 -->
          <i
            v-show="showRemoveBtn"
            @click="removeFundCode(index, holdUrl.code)"
            class="el-icon-circle-close animate__animated animate__rubberBand removeicon"
            title="删除"
          ></i>
        </el-col>
      </el-row>
    </div>
    <!-- 点击图片查看大图 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :width="dialogWidth"
      :append-to-body="true"
      :show-close="false"
    >
      <el-image style="width: 100%" :src="dialogImgUrl"> </el-image>
    </el-dialog>
    <!-- 添加基金弹框 -->
    <el-dialog
      :visible.sync="addFundDialog"
      :width="dialogWidth"
      :append-to-body="true"
      :show-close="false"
      center
    >
      <div style="padding: 20px">
        <div style="margin-bottom: 10px">请输入基金代码点击保存</div>
        <el-input placeholder="请输入基金代码" v-model="fundCode" clearable>
        </el-input>
        <div style="color: #f56c6c">
          支持批量添加,用'+'号分开,请确保您填写的基金代码真实有效,否则会影响展示结果
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addFundDialog = false">取 消</el-button>
        <el-button type="primary" @click="saveAddFund">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import http from "../../util/http";
import apiUrl from "../../util/api";

// 引入监听宽度的组件
import elementResizeDetectorMaker from "element-resize-detector";
export default {
  data() {
    return {
      // 默认打开图标
      myicon: "el-icon-folder-add",
      // 默认显示持有走势
      isShow: true,
      // 持有基金图片
      imageHoldData: [],
      // 查看大图
      dialogVisible: false,
      // 大图图片路径
      dialogImgUrl: "",
      // 基金代码
      fundCode: "",
      // 添加弹框
      addFundDialog: false,
      // 删除图标
      showRemoveBtn: false,
      // 弹框大小
      dialogWidth: "60%",
      // 时间
      nowTime: "00:00",
      // 屏幕缩小时的顶部编剧
      isMarginTop: false,
    };
  },
  mounted() {
    // 进页面默认刷新
    this.update();
    const erd = elementResizeDetectorMaker();
    // 监听页面宽度变化
    erd.listenTo(document.getElementsByClassName("box_body"), (element) => {
      this.$nextTick(() => {
        // 拿到左侧元素
        let leftDivWidth = element.offsetWidth;
        this.dialogWidth = leftDivWidth < 760 ? "80%" : "60%";
        console.log(element.offsetWidth);
        if (element.offsetWidth < 760) {
          this.isMarginTop = true;
        } else {
          this.isMarginTop = false;
        }
      });
    });
    setInterval(() => {
      // 获取当前时间
      this.nowTime = this.getnowTime();
    }, 1000);
  },
  methods: {
    getnowTime() {
      let date = new Date();
      let y = date.getFullYear();
      let h = date.getMonth() > 9 ? date.getMonth() : `0${date.getMonth()}`;
      let d = date.getDate() > 9 ? date.getDate() : `0${date.getDate()}`;
      let hh = date.getHours() > 9 ? date.getHours() : `0${date.getHours()}`;
      let mm =
        date.getMinutes() > 9 ? date.getMinutes() : `0${date.getMinutes()}`;
      let ss =
        date.getSeconds() > 9 ? date.getSeconds() : `0${date.getSeconds()}`;
      return `${hh}:${mm}:${ss}`;
    },
    // 删除按钮
    showRemove() {
      this.showRemoveBtn = !this.showRemoveBtn;
    },
    // 添加按钮
    addFund() {
      this.fundCode = "";
      this.addFundDialog = true;
    },
    // 确认添加
    saveAddFund() {
      if (!this.fundCode) {
        this.$message({
          message: "请填写基金代码",
          type: "error",
        });
        return;
      }
      // 支持添加多个，+号分隔开
      let fundCodeList = this.fundCode.split("+");
      // 判断缓存中是否有基金
      let fundCodeData = this.cookie.getCookie("codeList");

      if (fundCodeData) {
        // 从缓存中读取已添加的基金代码
        let codeList = JSON.parse(fundCodeData);
        // 过滤出正确的基金代码
        let filterSaveFund = [];
        // 循环添加的代码
        fundCodeList.forEach((inputcode) => {
          // 判断该基金代码是否存在
          let isRepeat = codeList.filter((item) => item === inputcode);
          // 长度为0表示该条基金不存在缓存中,可以被添加
          if (isRepeat.length === 0) {
            filterSaveFund.push(inputcode);
          }
        });

        // 封装数据到cookie
        let fund = {
          codeList: JSON.stringify([...codeList, ...filterSaveFund]),
        };
        // 存入cookie
        this.cookie.setCookie(fund, 180);
        // 关闭弹框
        this.addFundDialog = false;
        this.$message({
          message: "添加成功",
          type: "success",
        });
        this.update();
      } else {
        // 第一次存入缓存中
        fundCodeData = [];
        // 循环添加的代码
        fundCodeList.forEach((inputcode) => {
          fundCodeData.push(inputcode);
        });
        // 封装数据到cookie
        let fund = {
          codeList: JSON.stringify(fundCodeData),
        };
        this.cookie.setCookie(fund, 180);
        // 关闭弹框
        this.addFundDialog = false;
        this.$message({
          message: "添加成功",
          type: "success",
        });
        this.update();
      }
    },
    // 刷新按钮
    update() {
      this.imageHoldData = [];
      // 从缓存中读取基金代码
      let fundCodeData = this.cookie.getCookie("codeList");
      if (fundCodeData) {
        let codeList = JSON.parse(fundCodeData);
        if (codeList && codeList.length > 0) {
          // 循环基金代码
          codeList.forEach((code, i) => {
            // 图片路径后面追加随机数刷新图片
            let url = `http://j4.dfcfw.com/charts/pic6/${code}.png?v=${
              Math.random() * 10
            }`;
            this.imageHoldData[i] = {
              url: url,
              code: code,
            };
            // 更新视图
            this.$forceUpdate();
          });
        }
      } else {
        this.$message({
          message: "您还为添加任何基金,请先添加",
          type: "warning",
        });
      }
    },
    // 展开折叠
    taggleimg() {
      let isShow = document.querySelector("#isShow");
      if (this.myicon === "el-icon-folder-add") {
        // 折叠
        this.myicon = "el-icon-folder-remove";
        // 显示动画
        isShow.classList.remove("animate__bounceInUp");
        isShow.classList.add("animate__bounceOutRight");
        setTimeout(() => {
          this.isShow = false;
        }, 800);
      } else {
        // 展开显示
        this.myicon = "el-icon-folder-add";
        this.isShow = true;
        // 显示动画
        isShow.classList.remove("animate__bounceOutRight");
        isShow.classList.add("animate__bounceInUp");
      }
    },
    // 确认删除
    removeFundCode(index, code) {
      this.$confirm(`确定删除代码为：${code}的基金吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        // 读取基金列表
        let fundList = JSON.parse(this.cookie.getCookie("codeList"));
        // 删除基金代码
        fundList.splice(index, 1);
        // 更新cookie
        let fund = {
          codeList: JSON.stringify(fundList),
        };
        this.cookie.setCookie(fund, 7);
        this.showRemoveBtn = false;
        this.update();
        this.$message({
          type: "success",
          message: "删除成功!",
        });
      });
    },
  },
};
</script>

<style scoped>
.box_body {
  padding: 10px;
}
.margin-bottom {
  margin-bottom: 5px;
}
img {
  width: 100%;
}
.tag-hold {
  display: flex;
  height: 30px;
  border-radius: 5px;
  line-height: 30px;
  padding-left: 10px;
  color: white;
  opacity: 0.8;
  margin-bottom: 10px;
}

.tag-follow {
  height: 30px;
  background-color: #67c23a;
  border-radius: 5px;
  line-height: 30px;
  padding-left: 10px;
  color: white;
  margin-bottom: 10px;
}
.heade-title {
  display: flex;
  justify-content: center;
  margin-bottom: -35px;
  color: white;
}
.updatetxt {
  position: absolute;
  right: 0;
}
i,
span {
  cursor: default;
}
.el-dialog__header {
  display: none !important;
}
.el-dialog__body {
  padding: 5px !important;
  color: #606266;
  font-size: 14px;
  word-break: break-all;
}
.el_col_relative {
  position: relative;
}
.removeicon {
  position: absolute;
  right: 0;
  top: -12px;
  font-size: 28px;
  color: #f56c6c;
}
.changeicon {
  position: absolute;
  right: 0;
  top: -12px;
  font-size: 28px;
  color: #67c23a;
}
.fundImage {
  width: 100%;
  height: auto;
  transform: scale(1);
  transition: transform 0.3s ease 0s;
  opacity: 0.7;
  border-radius: 5px;
}

.fundImage:hover {
  transform: scale(1.01);
}
.timestyle {
  font-weight: 700;
  font-family: "隶属";
}
.headerIsMargintop {
  margin-top: 35px;
}
</style>